<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Job\EsJob;
use App\Library\Common;
use App\Model\Areainfo;
use App\Model\data\CurrentShopData;
use App\Model\DeliveryTpl;
use App\Model\DistributionCenter;
use App\Service\EsService;
use App\Service\ProductService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;

class EsController extends AbstractController
{
    const ES_TYPE = [1=>'SPU',2=>'SKU',3=>'VIDEO',4=>'SHOP',5=>'CENTER',6=>'STAR'];
    /**
     *全等于可用
     *$where['desc.id']  = 41;
     */
//        $where['es_key']  = 'SPU_41';全等于可用
//        $where['desc.id']  = 41;
/**
*排序方法
 **/

//$attrs['order_by'] = $params['order_by']==1?'min_price ASC':'max_price DESC';

    /**
     * @Inject
     * @var EsService
     * */
    private $es;


    public function list(){
        $params = $this->request->all();
        $this->validation($params,[
            'key_word'=>['string'],
            'type'=>['integer','required','between:1,4'],
            'min_price'=>['numeric'],
            'max_price'=>['numeric'],
            'industry_ids'=>['array'],
            'area_id'=>['integer'],
            'order_by'=>['integer','between:1,3'],
            'industry_ids.*'=>['integer','exists:fly_industry,id'],
            'center_id'=>['integer','exists:fly_center,id'],
            'is_origin_made'=>['boolean'],
            'is_free_delivery'=>['boolean'],
            'goods_type'=>'integer|between:1,3',
        ]);


        $attrs = [];
        $where = [];

        if(isset($params['type'])){
            $where['es_type'] = self::ES_TYPE[$params['type']];
        }
//        关键词
        if($params['key_word']){
            $where['key_word'] = $params['key_word'];
        }
        $where['is_show'] =1;
        $where['is_illegal'] =0;
        $where['check_status'] = 1;
        $where['shop_info.shop_state'] = 1;


        var_dump($where);
//        分页
        $size = $params['size']?:10;
        $current = $params['current']?:1;
        $limit = $size*($current-1);
        $attrs['offset'] = $limit;
        $attrs['limit'] =  $size;

//        排序
        if(isset($params['order_by'])){
//            1综合  2销量最高  3价格升序
            if($params['order_by']==2){
                $attrs['order_by'] = 'sales_actual DESC';
            }elseif ($params['order_by']==3){
                $attrs['order_by'] = 'min_price ASC';
            }
        }

//        集散地
        if(isset($params['area_id'])&&$params['area_id']!=''){
            $level_set = ['2'=>'province_id','3'=>'city_id','4'=>'area_id','5'=>'street_id'];
            $area_info = (New Areainfo())->find($params['area_id']);
            if(!$area_info){
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID, '不存在的地区id');
            }else{
                $level  =   $area_info->level;
                $center_where[$level_set[$level]] = $params['area_id'];
                $ids = [];
                $ids = DistributionCenter::query()
                    ->where($center_where)->pluck('id');
                if($ids){
                    $ids  = $ids->toArray();
                }
                $where['desc.center_id'] = $ids;
            }
        }


//        行业ids
        if(isset($params['industry_ids'])&&$params['industry_ids']!=[]){
            $where['desc.industry_id'] = $params['industry_ids'];
        }

//        s是否原产地
        if(isset($params['is_origin_made'])&&$params['is_origin_made']==1){
            $where['desc.is_origin_made'] = $params['is_origin_made'];
        }
//        包邮
        if(isset($params['is_free_delivery'])&&$params['is_free_delivery']==1){
            $where['desc.delivery_info.is_free'] = 1;
        }
//        搜索条件
        if(isset($params['is_sell'])&&$params['is_sell']!=''){
            $where['is_sell'] = $params['is_sell'];
        }
        if(isset($params['is_show'])&&$params['is_show']!=''){
            $where['is_show'] = $params['is_show'];
        }
//        范围搜索价格
        if(isset($params['min_price'])&&$params['min_price']!=''){
            $where['min_price'] = ['>='=>$params['min_price']];
        }
        if(isset($params['max_price'])&&$params['max_price']!=''){
            $where['max_price'] = ['<='=>$params['max_price']];
        }
        if(isset($params['eid'])&&$params['eid']!=''){
            $where['eid'] = $params['eid'];
        }
        $list = $this->es->select($where,$attrs,false);
        $count = $this->es->selectCount($where,$attrs);
        $return=   [
            'list'=>$list,
            'count'=>$count,
        ];
        return $this->jsonResponse->success($return,'返回');
    }

//    创建表
    public function create_index(){

        if($this->es->createIndex()){
            return $this->jsonResponse->success([],'创建成功或已存在');
        }else{
            return $this->jsonResponse->error([],'创建失败');
        }

    }

//    删除表
    public function del_index(){
        if($this->es->deleteIndex()){
            return $this->jsonResponse->success([],'删除成功');
        }else{
            return $this->jsonResponse->error([],'删除失败');
        }
    }

    public function detail()
    {
        $params = $this->request->inputs(['id','type']);
        $this->validation($params,[
            'id'=>['required','integer'],
            'type'=>['required','integer'],
        ]);
        $info = $this->es->es_info(intval($params['id']),intval($params['type']));
        return $this->jsonResponse->success($info,'返回');
    }


//    删除文档
    public function del()
    {
        $params = $this->request->inputs(['id','type']);
        $this->validation($params,[
            'id'=>['required','integer'],
            'type'=>['required','integer'],
        ]);
        $res =  $this->es->deleteDoc($params['id'],$params['type']);
        if($res){
            return $this->jsonResponse->success($res,'返回');
        }else{
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR,'未删除或不存在的文档');
        }
    }

    //    get_mapping
    public function mapping()
    {
        $res =  $this->es->getMapping();
        return $this->jsonResponse->success($res,'返回');
    }

    public function add(){
        $params = $this->request->inputs(['id','type']);
        $this->validation($params,[
            'id'=>['required','integer'],
            'type'=>['required','integer'],
        ]);
        try {
            $this->es->es_add(intval($params['id']),intval($params['type']));
            return $this->jsonResponse->success([],'插入成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'插入失败'.$exception->getMessage());
        }

    }

}
